package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.constants.EsConstants;
import com.atguigu.common.utils.R;
import com.atguigu.feign.to.es.SkuEsModel;
import com.atguigu.gulimall.search.service.EsSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EsSaveServiceImpl implements EsSaveService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public boolean productSaveEs(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulk = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            bulk.add(new IndexRequest(EsConstants.PRODUCT_INDEX)
                    .id(skuEsModel.getSkuId().toString())
                    .source(JSON.toJSONString(skuEsModel), XContentType.JSON));
        }

        BulkResponse bulk1 = client.bulk(bulk, RequestOptions.DEFAULT);
        boolean b = bulk1.hasFailures();
        if(b){
            List<String> collect = Arrays.stream(bulk1.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.info("ES批量新增索引出现错误：{}",collect);
        }

        return b;
    }
}
